package com.ailargemodel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.ailargemodel.common.constant.UserConstant;
import cn.hutool.core.util.StrUtil;
import com.ailargemodel.common.BaseResponse;
import com.ailargemodel.common.ErrorCode;
import com.ailargemodel.common.RedisLimiterManager;
import com.ailargemodel.common.exception.BusinessException;
import com.ailargemodel.common.utils.ResultUtil;
import com.ailargemodel.mapper.QuesttionMapper;
import com.ailargemodel.pojo.Questtion;
import com.ailargemodel.pojo.RedisConstants;
import com.ailargemodel.pojo.User;
import com.ailargemodel.service.AIService;
import com.ailargemodel.service.UserService;
import com.ailargemodel.utils.AIUtils;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ailargemodel.mapper.UserMapper;
import com.google.gson.Gson;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import javax.management.Query;

import java.sql.Date;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.ailargemodel.common.constant.UserConstant.USER_LOGIN_STATE;


/**
* @author 喜洋洋
* @description 针对表【user(存储学生相关的信息)】的数据库操作Service实现
* @createDate 2024-07-28 15:43:44
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
   private final String salt = "AiBailian";

    @Autowired
    public QuesttionMapper questtionMapper;

   @Autowired
   private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AIUtils aiUtils;

   @Autowired
   private UserMapper userMapper;

    @Override
    public BaseResponse loginandregister(String name, String studyId, HttpServletRequest request, HttpServletResponse response) throws NoApiKeyException, InputRequiredException {
//        判断 用户名 或者 学号 已存在的
        User user = userMapper.selectUser(name,studyId);

        User safeuser = new User();
//     未注册 , 登录
        if(user == null){
//      添加到数据库
            Instant nowTime = Instant.now();

            safeuser = safeuser.builder()
                    .name(name)
                    .studyId(studyId)
                    .questionNumber(0)
                    .createTime(Date.from(nowTime))
                    .build();
            save(safeuser);
           log.info("注册成功!!!");
            //        信息脱敏
            User safeUser= new User();
            safeUser = safeUser.builder()
                    .name(name)
                    .studyId(studyId)
                    .conversationId(1)
                    .build();
//                记录用户的登录态
            HttpSession session = request.getSession();
            session.setAttribute(USER_LOGIN_STATE,safeUser);
            String sessionId = session.getId();
            request.setAttribute(USER_LOGIN_STATE,safeUser);
//            request.getAttribute(USER_LOGIN_STATE);
        } else if (user != null) {
//        获取当前用户的 最大 conversationId
//            需要先判空
            int maxConversationId = 0;
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("study_id",studyId);
            List<Questtion> questtion = questtionMapper.selectList(queryWrapper);
            if (questtion != null) {
                maxConversationId = questtion.size();
            }
            //        信息脱敏
            safeuser = safeuser.builder()
                    .id(user.getId())
                    .name(user.getName())
                    .studyId(user.getStudyId())
                    .questionNumber(user.getQuestionNumber())
                    .conversationId(maxConversationId)
                    .build();
//                记录用户的登录态
//            HttpSession session = request.getSession();
//            session.setAttribute(USER_LOGIN_STATE,safeUser);
//            String sessionId = session.getId();
//            request.getAttribute(USER_LOGIN_STATE);
            request.setAttribute(USER_LOGIN_STATE,safeuser);
        }
        //            尝试redis 存储 session
        String Key = RedisConstants.LOGIN_CODE_KEY + request.getSession().getId();
/*        Map<String, Object> userMap = BeanUtil.beanToMap(safeuser, new HashMap<>(),
                CopyOptions.create() //在存储为map时要保证值全为String
                        .setIgnoreNullValue(true) //忽略空值
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue == null ? "" : fieldValue.toString()));*/
        Gson gson = new Gson();
        Map<String, String> userMap = new HashMap<>();
        userMap.put(request.getSession().getId(), gson.toJson(safeuser));

        stringRedisTemplate.opsForHash().putAll(Key,userMap);
        stringRedisTemplate.expire(Key, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);


        // 将 login_ + userVO.getId() 加密并生成cookie返回客户端
        String encryption = MD5Encoder.encode(("login_" + safeuser.getStudyId()).getBytes());
        Cookie cookie = new Cookie("loginCookie", encryption);
        //设置cookie失效时间(秒)-7天和路径
        // 默认实现七天免登录 7* 24 * 3600
        cookie.setMaxAge(604800);
//        cookie.setPath("/") 表示这个Cookie将被所有以 /api 开头的路径所访问。这意味着只要请求的URL路径以 /api 开始，浏览器就会将这个Cookie附加到HTTP请求中。
        cookie.setPath("/api");
        response.addCookie(cookie);

        //将用户标记为在线
      /*  主键（RedisConstants.LOGIN_ONLINE_KEY）：用于标识整个哈希表。
        字段（safeuser.getStudyId()）：用于标识哈希表中的具体项。
        值（System.currentTimeMillis() / 1000）：用于存储具体的数值，这里是时间戳。*/
//        stringRedisTemplate.opsForHash().put(RedisConstants.LOGIN_ONLINE_KEY, String.valueOf(safeuser.getStudyId()), String.valueOf(System.currentTimeMillis() / 1000));
//        对AI的 功能做 一个 预设
  /*      aiUtils.callWithMessage("假如你是一位算法老师，擅长对题目进行1翻译，2解读，3思路引导，以及对于代码，能进行4代码纠错，5质量评估，最后还能6回答相关的算法代码问题，以下的问题都是围绕这六点展开，请使用中文对一下问题进行回答");
*/
        return ResultUtil.sucess(safeuser, request.getSession().getId());
    }

    @Override
    public BaseResponse userLogOut(String studyId, HttpServletRequest request, HttpServletResponse response, String cookie) {
//        这个 退出功能 , 和保持会话的能力 只有 浏览器有 , APIfox上每次是模拟一个会话
        //清除在线状态
        stringRedisTemplate.opsForHash().delete(RedisConstants.LOGIN_ONLINE_KEY, String.valueOf(studyId));
        //清除登陆用户信息
        String key = RedisConstants.LOGIN_CODE_KEY + request.getSession().getId();
        if (StrUtil.isNotBlank(cookie)) {
            //清除cookie
            Cookie newCookie = new Cookie("loginCookie", null);
            newCookie.setMaxAge(0);
            newCookie.setPath("/api");
            response.addCookie(newCookie);
        }
        if (stringRedisTemplate.delete(key) ) {
            return ResultUtil.sucess(ErrorCode.SUCCESS);
        }else {
            return ResultUtil.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取当前登录用户
     * @param sessionId
     * @return
     */
    @Override
    public User getLoginUser(String sessionId) {
        // request为空返回null
        if (Objects.isNull(sessionId)){
            return null;
        }
        String key = RedisConstants.LOGIN_CODE_KEY + sessionId;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        String bytes = (String) userMap.get(sessionId);
        Gson gson = new Gson();
        User user = gson.fromJson(bytes, User.class);
        return user;
    }
}




